/**
 * 
 */
package com.eis.admin.mvc.common.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.eis.admin.mvc.common.utils.MVCConstants;
import com.eis.admin.mvc.controller.base.MVCBaseController;
import com.eis.persist.model.user.PersistUser;

/**
 * @author sh-panwei01
 *
 */
public class SessionObjectsInterceptor extends HandlerInterceptorAdapter {
	private static final Logger logger = LoggerFactory.getLogger(SessionObjectsInterceptor.class);
	
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		logger.debug("step into SessionObjectsInterceptor::preHandle");
		PersistUser persistUser = (PersistUser)request.getSession().getAttribute(MVCConstants.USER_SESSION_KEY);
		String requetUri = request.getRequestURI();
		
		
		if (persistUser == null && (!(requetUri.indexOf("reLogin") > -1) 
				&& !(requetUri.indexOf("adminLogin") > -1) && !(requetUri.indexOf("logout") > -1)
				&& !(requetUri.indexOf("submitLogin") > -1))) {
			response.sendRedirect(request.getContextPath() + "/web/reLogin");
			return false;
		}
		
		if (handler instanceof MVCBaseController) {
			MVCBaseController baseController = (MVCBaseController) handler;
			
			// warn & error messages
			if (request.getParameter(MVCConstants.WARN_MESSAGE_KEY) != null && request.getParameter(MVCConstants.WARN_MESSAGE_KEY).length() > 0) {
				baseController.setWarningMessage(request, request.getParameter(MVCConstants.WARN_MESSAGE_KEY));
			}
			
			if (request.getParameter(MVCConstants.ERROR_MESSAGE_KEY) != null && request.getParameter(MVCConstants.ERROR_MESSAGE_KEY).length() > 0) {
				baseController.setErrorMessage(request, request.getParameter(MVCConstants.ERROR_MESSAGE_KEY));
			}
		}
		
		return true;

	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

		logger.debug("step into SessionObjectsInterceptor::postHandle");
		PersistUser persistUser = (PersistUser)request.getSession().getAttribute(MVCConstants.USER_SESSION_KEY);
		if (persistUser != null) {
			request.setAttribute(MVCConstants.USER_ID_REQUEST_KEY, String.valueOf(persistUser.getId()));
		}
		
		if (handler instanceof MVCBaseController) {
			MVCBaseController baseController = (MVCBaseController) handler;
			request.setAttribute("tabId", baseController.getTabId());
		}
	}
}
